﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zzcore.Model;
using Masuit.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Zzcore.Controllers
{
    public class DepartmentController : BaseController
    {
        private readonly ILogger<DepartmentController> _logger;
        public DepartmentController(ILogger<DepartmentController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index()
        {
            JArray data = GetDepartmentTree(0).Result;
            return RenderJson(data: data);
        }

        [NonAction]
        public async Task<JArray> GetDepartmentTree(long pid)
        {
            JArray data = new();
            List<Department> departments = await _fsql.Select<Department>().Where(m => m.Pid == pid).OrderBy("sortid asc").ToListAsync();
            if (departments != null && departments.Count > 0)
            {
                foreach (var department in departments)
                {
                    JObject jo_menu = JObject.FromObject(department);
                    jo_menu.Add("children", GetDepartmentTree(department.Id).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        [HttpPost]
        public async Task<IActionResult> GetAllParentByChildrenId([FromForm] long id) {
            await GetAllParent(id);

            JObject data = new();
            departments.Reverse();
            data.Add("parent_departments", JArray.FromObject(departments));
            List<Department> children_departments = await _fsql.Select<Department>().Where(d => d.Pid == id).ToListAsync();
            data.Add("children_departments", children_departments == null ? null : JArray.FromObject(children_departments));
            return new JsonResult(new { status = "success", message = "获取所有父类成功", code = 1, data });
        }

        private readonly List<Department> departments = new(); // 所有部门父部门
        [NonAction]
        public async Task GetAllParent(long id)
        {
            // 查询当前节点信息
            Department department = await _fsql.Select<Department>().Where(m => m.Id == id).ToOneAsync();
            if (department != null)
            {
                departments.Add(department);
                await GetAllParent(department.Pid);
            }
        }

        [HttpPost]
        public async Task<IActionResult> GetChildren([FromForm] long id)
        {
            List<Department> departments = await _fsql.Select<Department>().Where(d => d.Pid == id).OrderBy("sortid asc").ToListAsync();
            return new JsonResult(new { status = "success", message = "保存成功", code = 1, data = departments });
        }

        [HttpPost]
        public async Task<IActionResult> Save([FromForm] string strjsondepartments)
        {
            List<Department> departments = JsonConvert.DeserializeObject<List<Department>>(strjsondepartments);
            // 根据索引排序
            departments.ForEach(d => d.Sortid = departments.IndexOf(d) + 1);
            List<Department> insertDepartments = new();
            List<Department> updateDepartments = new();
            foreach (var department in departments)
            {
                if (department.Id == 0)
                {
                    // 增加
                    insertDepartments.Add(department);
                }
                else {
                    // 更新
                    updateDepartments.Add(department);
                }
            }
            insertDepartments.ForEach(idp => Console.WriteLine(idp.ToString()));
            updateDepartments.ForEach(udp => Console.WriteLine("update" + udp.ToString()));
            JObject data = new();
            if (insertDepartments.Count > 0) {
                // 执行插入操作
                int insertAffrows = await _fsql.Insert<Department>(insertDepartments).ExecuteAffrowsAsync();
                data.Add("insertAffrows", insertAffrows);
            }
            if (updateDepartments.Count > 0)
            {
                // 执行更新操作
                int updateAffrows = await _fsql.Update<Department>().SetSource(updateDepartments).ExecuteAffrowsAsync();
                data.Add("updateAffrows", updateAffrows);
            }
            return new JsonResult(new { status = "success", message = "保存成功", code = 1, data });
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            // 该部门下有子部门不让删除
            Department department = await _fsql.Select<Department>().Where(d => d.Pid == id).ToOneAsync();
            if (department != null)
            {
                return RenderJson(status: "failed", message: "该部门下拥有子部门，不允许删除", code: -1, data: null);
            }

            int affrows = await _fsql.Delete<Department>().Where(d => d.Id == id).ExecuteAffrowsAsync();
            
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] Department department) {
            int affrows = await _fsql.Update<Department>().SetSource(department).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            Department department = await _fsql.Select<Department>().Where(d => d.Id == id).ToOneAsync();
            return RenderJson(data: department);
        }

        [HttpPost]
        public async Task<IActionResult> Drag([FromForm] string strjsondepartments)
        {
            List<Department> departments = JsonConvert.DeserializeObject<List<Department>>(strjsondepartments);
            departments.ForEach(d => d.Sortid = departments.IndexOf(d) + 1);
            int affrows = await _fsql.Update<Department>().SetSource(departments).ExecuteAffrowsAsync();
            return new JsonResult(new { status = "success", message = "拖拽更新成功", code = 1, data = affrows });
        }
    }
}
